package com.baoyouqun.domain.VO;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baoyouqun.domain.Enum.SystemConfigType;
import com.baoyouqun.entity.SystemConfig;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Data
public class LeopardNumberRuleDTO implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    private String id;

    @ApiModelProperty(value = "豹子号规则列表（使用内部类封装键值对）")
    private List<RuleItem> ruleList = new ArrayList<>(); // 初始化为空列表，避免null

    /**
     * 从SystemConfig转换（反序列化为List<RuleItem>）
     */
    public static LeopardNumberRuleDTO fromSystemConfig(SystemConfig systemConfig) {
        if (systemConfig == null || !SystemConfigType.LEOPARD_NUMBER_RULE.equals(systemConfig.getConfigType())) {
            throw new IllegalArgumentException("无效的豹子号规则配置数据");
        }

        LeopardNumberRuleDTO dto = new LeopardNumberRuleDTO();
        dto.setId(systemConfig.getId());

        String ruleJson = systemConfig.getInfo8();
        if (ruleJson != null && !ruleJson.trim().isEmpty()) {
            try {
                // 反序列化为List<RuleItem>，避免Map的类型问题
                List<RuleItem> parsedList = JSON.parseObject(
                        ruleJson,
                        new TypeReference<List<RuleItem>>() {
                        }
                );
                // 过滤空元素，确保列表纯净
                dto.setRuleList(filterValidItems(parsedList));
            } catch (Exception e) {
                throw new RuntimeException("豹子号规则配置反序列化失败: " + ruleJson + ", 错误: " + e.getMessage(), e);
            }
        }

        return dto;
    }

    /**
     * 过滤无效的RuleItem（排除null或字段为空的项）
     */
    private static List<RuleItem> filterValidItems(List<RuleItem> items) {
        if (items == null) {
            return new ArrayList<>();
        }
        return items.stream()
                .filter(Objects::nonNull) // 排除null元素
                .filter(item -> {
                    // 排除规则名或号码为空的项
                    return item.getRuleName() != null && !item.getRuleName().trim().isEmpty()
                            && item.getNumber() != null && !item.getNumber().trim().isEmpty();
                })
                .collect(Collectors.toList());
    }

    /**
     * 转换为SystemConfig（序列化为List<RuleItem>的JSON数组）
     */
    public SystemConfig toSystemConfig(SystemConfig config) {
        if (config == null) {
            throw new IllegalArgumentException("SystemConfig参数不能为空");
        }

        config.setConfigType(SystemConfigType.LEOPARD_NUMBER_RULE);
        config.setConfigName(SystemConfigType.LEOPARD_NUMBER_RULE.getDesc());

        try {
            // 先过滤无效项，再序列化
            List<RuleItem> validItems = filterValidItems(this.ruleList);
            config.setInfo8(JSON.toJSONString(validItems));
        } catch (Exception e) {
            throw new RuntimeException("豹子号规则配置序列化失败: " + e.getMessage(), e);
        }

        return config;
    }

    /**
     * 内部类：封装单个规则（规则名+号码）
     */
    @Data
    public static class RuleItem implements Serializable {
        @Serial
        private static final long serialVersionUID = 1L;

        @ApiModelProperty(value = "规则名称（如AAAA、ABABCDCD）")
        private String ruleName; // 对应原Map的key

        @ApiModelProperty(value = "号码示例（如13929111155）")
        private String number; // 对应原Map的value，用String避免数字解析问题
    }
}